package com.epalmpay.service.operator.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.operator.SysLogQueryDTO;
import com.epalmpay.dto.operator.SysTaskLogInDTO;
import com.epalmpay.dto.operator.SysTaskLogListOutDTO;
import com.epalmpay.entity.Page;
import com.epalmpay.entity.SysTaskLog;
import com.epalmpay.entity.Syslog;
import com.epalmpay.mapper.SysTaskLogMapper;
import com.epalmpay.mapper.SyslogMapper;
import com.epalmpay.service.operator.ISysLogService;
import com.epalmpay.util.DateUtil;
import com.epalmpay.util.Tools;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import com.epalmpay.enumdef.CommonEnum.RunStatus;

/**
 * Created by lifayi on 2017/5/3.
 */
@Service
public class SysLogServiceImpl implements ISysLogService {

    @Autowired
    private SyslogMapper syslogMapper;
    @Resource
    private SysTaskLogMapper sysTaskLogMapper;

//    public int addSysLog(SysLogInDTO sysLogInDTO) throws Exception {
//        Syslog syslog = new Syslog();
//        syslog.setUserId(sysLogInDTO.getUserId());
//        syslog.setUserName(sysLogInDTO.getUsername());
//        syslog.setIp(sysLogInDTO.getIp());
//        syslog.setContent(sysLogInDTO.getContent());
//        syslog.setGroupId(sysLogInDTO.getGroupId());
//        syslog.setGmtCreate(new Date());
//
//        return syslogMapper.insert(syslog);
//    }

    public int addSysLog(Long userId,String userName,String ip,String content,Long groupId) throws Exception {
        Syslog syslog = new Syslog();
        syslog.setUserId(userId);
        syslog.setUserName(userName);
        syslog.setIp(ip);
        syslog.setContent(content);
        syslog.setGroupId(groupId);
        syslog.setGmtCreate(new Date());

        return syslogMapper.insert(syslog);
    }

    public List<Syslog> listSysLog(SysLogQueryDTO sysLogQueryDTO, Page page) throws Exception {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Syslog syslog = new Syslog();
        syslog.setPage(page);
        syslog.setUserName(sysLogQueryDTO.getUserName());
        syslog.setGroupId(sysLogQueryDTO.getGroupId());

        String dateStart = sysLogQueryDTO.getDateStart();
        String dateEnd = sysLogQueryDTO.getDateEnd();

        if(!Tools.isEmpty(dateStart)) {
            Date dateStartDate = dateFormat.parse(dateStart);
            syslog.setDateStart(dateStartDate);
        }

        if(!Tools.isEmpty(dateEnd)) {
            Date dateEndDate = dateFormat.parse(dateEnd);
            syslog.setDateEnd(DateUtil.getDateNext(dateEndDate, 1));
        }

        List<Syslog> syslogList;
//        if(sysLogQueryDTO.getGroupId() == 0) {
            syslogList = syslogMapper.sysLoglistPage(syslog);
//        } else {
//            syslogList = syslogMapper.merchantSysLoglistPage(syslog);
//        }

        return syslogList;
    }


    public int delSysLog(SysLogQueryDTO sysLogQueryDTO) throws Exception {
        List<Long> delItems = sysLogQueryDTO.getDelItems();
        Long groupId = sysLogQueryDTO.getGroupId();

        if(delItems.get(0) == -1) {
            return syslogMapper.deleteAll(groupId);
        } else {
            for(int i = 0; i < delItems.size(); i ++) {
                syslogMapper.deleteById(groupId, delItems.get(i));
            }
            return 1;
        }
    }
    
    public SysTaskLogListOutDTO getSysTaskLogList(SysTaskLogInDTO sysTaskLogInDTO,Page page) throws Exception {
    	SysTaskLogListOutDTO result = new SysTaskLogListOutDTO();
    	
    	Map<String,Object> param=new HashMap<String,Object>();
		param.put("taskType", sysTaskLogInDTO.getTaskType());
		param.put("resultStatus", sysTaskLogInDTO.getResultStatus());
		param.put("startDate", sysTaskLogInDTO.getStartDate());
		param.put("endDate", sysTaskLogInDTO.getEndDate());//月份
				
		int sumCount = sysTaskLogMapper.selectSysTaskLogListCount(param);
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return result;
		
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		result.setSysTaskLogList(sysTaskLogMapper.selectSysTaskLogList(param));
    	
    	return result;
    }
    
    public SysTaskLogListOutDTO sysTaskLogReRun(SysTaskLogInDTO sysTaskLogInDTO) throws Exception{
    	SysTaskLogListOutDTO result = new SysTaskLogListOutDTO();
    	
    	Long sysTaskLogId = sysTaskLogInDTO.getSysTaskLogId();
    	if(sysTaskLogId != null){
    		SysTaskLog record = sysTaskLogMapper.selectByPrimaryKey(sysTaskLogId);
    		if(record.getResultStatus() == RunStatus.Success.getType()){
    			throw new ApplicationException(Rescode.FAIL,"计划任务已经执行成功！");
    		}
    		//此处重跑逻辑
    	}
    	else{
        	Map<String,Object> param=new HashMap<String,Object>();
    		param.put("taskType", sysTaskLogInDTO.getTaskType());
    		param.put("taskDate", sysTaskLogInDTO.getTaskDate());

    		SysTaskLog record = sysTaskLogMapper.selectSysTaskLogByTypeAndDate(param);
    		if(record != null && record.getResultStatus() == RunStatus.Success.getType()){
    			throw new ApplicationException(Rescode.FAIL,"计划任务已经执行成功！");
    		}
    		//此处重跑逻辑    		
    	}
    	
    	return result;
    }
    
    /***记录计划任务处理日志
     * 如果没记录过，插入记录。如果记录过，
     * @param taskType
     * @param taskDate
     * @param resultStatus
     * @return
     * @throws Exception
     */
    public int recordSysTaskLog(int taskType,Date taskDate,int resultStatus) throws Exception{
    	return recordSysTaskLog(taskType,taskDate,resultStatus,null);
    }
    
    //插入计划任务处理日志
    public int recordSysTaskLog(int taskType,Date taskDate,int resultStatus,String memo) throws Exception{
    	int result =0;
    	
    	Map<String,Object> param=new HashMap<String,Object>();
		param.put("taskType", taskType);
		param.put("taskDate", taskDate);

		SysTaskLog oldRecord = sysTaskLogMapper.selectSysTaskLogByTypeAndDate(param);
        if(oldRecord  == null){
	    	SysTaskLog record = new SysTaskLog();
	    	record.setGmtCreate(new Date());
	    	record.setGmtModified(new Date());
	    	record.setTaskType(taskType);
	    	record.setTaskDate(taskDate);
	    	record.setResultStatus(resultStatus);
	    	record.setMemo(memo);
	    	result = sysTaskLogMapper.insert(record);
        }
        else{
        	oldRecord.setGmtModified(new Date());
        	oldRecord.setResultStatus(resultStatus);
        	oldRecord.setRunTimes((oldRecord.getRunTimes()==null?0:oldRecord.getRunTimes())+1);
        	oldRecord.setMemo((oldRecord.getMemo()==null?"":oldRecord.getMemo()) + (memo==null?"":memo));
        	result = sysTaskLogMapper.updateByPrimaryKeySelective(oldRecord);
        }
    	
    	return result;    	
    }

}
